package com.FastTorch;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.admin.DevicePolicyManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;

public final class GlobalLogic{
	
	
	public static int brightnessMode=-1;
	public static int brighness=0;

	public static final int OFF_MODE=0;
	public static final int ON_LED_MODE=1;
	public static final int ON_SCREEN_MODE=2;
	public static final int PREF_MODE=33;
	public static final int EXIT_MODE=100;
	public static final int PAUSE_MODE=10;
	
	public static int curentMode=0;
	public static int oldMode=0;
	
	public static final int RUN_FROM_WIDGET=110;
	public static final int RUN_FROM_ACTIVITY=1000;
	
	public static int runedFrom=RUN_FROM_ACTIVITY;
	
	public static Boolean readyToExitSmall=false;
	public static Boolean readyToExitBig=false;
		
	public static SharedPreferences prefs;
	
	public static Context lastContext=null;
	
	
	public static Boolean isScreenOff=false;
	
	 public static final int NOTIFY_ID = 101; 
	 public static NotificationManager mNotifyMgr; 
	 
	 public static String ACTION_TAKE_RECEIVER = "ActionTake";
	 public static String ACTION_OFF_RECEIVER = "ActionOff";
	 

	 private static Camera camera;
	 private static int cameraId = -1;
		
	 private static void runScreenTorch(Context context){
		
		 	if (MainFastTorchActivity.handleToClose!=null){
		 		MainFastTorchActivity.handleToClose.finish();
		 		MainFastTorchActivity.handleToClose=null;
		 	}
			 Intent runs = new Intent(context, MainFastTorchActivity.class);
			  		 
			 runs.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
			 runs.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
			 runs.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			
			 context.getApplicationContext().startActivity(runs);
			
			 
	  }

	 static ShowDialog mDialog;
	 public static void setDialogListener(ShowDialog l) {
		 mDialog = l;
		}
	 
	 static ShowDialog mDialog1;
	 public static void setDialogListener1(ShowDialog l) {
		 mDialog1 = l;
		}
	 
	public static final String COUNTER_SETTINGS = "MY_COUNTER";
	
	public static Boolean getSetedScreen(Context context){
		
		 SharedPreferences sp = context.getSharedPreferences(COUNTER_SETTINGS, 
	                Context.MODE_PRIVATE);
		 return sp.getBoolean("seted", false);
		 		
	}
	
	public static int getCount(Context context){
		SharedPreferences sp = context.getSharedPreferences(COUNTER_SETTINGS, 
                Context.MODE_PRIVATE);
		return sp.getInt("count", 0);
	}
	
	
	public static Boolean CheckCount(Context context){
		
		
		 SharedPreferences sp = context.getSharedPreferences(COUNTER_SETTINGS, 
	                Context.MODE_PRIVATE);
		 int count=sp.getInt("count", 0);
		 
		 count++;
		 Editor e=sp.edit();
		 e.putInt("count", count);
		 e.commit();
		 
		 if (count!=6){
			 return false;
		 }
		return true;
	}
	
	
	public static int findFrontFacingCamera(Context context) {
		    cameraId = -1;
		    if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
		    	return cameraId;
		    }
		    // Search for the front facing camera
		    int numberOfCameras = Camera.getNumberOfCameras();
		    for (int i = 0; i < numberOfCameras; i++) {
		      CameraInfo info = new CameraInfo();
		      Camera.getCameraInfo(i, info);
		      if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
		      
		        cameraId = i;
		       
		        break;
		      }
		    }
		    return cameraId;
		  }
	 
	public static AlertDialog.Builder ad;
	public static void showDialog(Context context){

		if (MainFastTorchActivity.handleToClose==null){
			Handler handler = new Handler(); 
		    handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub		
					mDialog1.onShow();
					}
			}, 500); 
		}
		else{
			mDialog1.onShow();
		}
		
	}
	private static int onTorch(Context context){
			 
			 findFrontFacingCamera(context);
						
			 
				if (cameraId>=0 && 
						(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH) || 
						 (getCount(context)>0) && getSetedScreen(context))
						){ 
					 
					if (camera==null){
						try {
							camera = Camera.open(cameraId);		
							
							Parameters params = camera.getParameters();			
							params.setFlashMode(Parameters.FLASH_MODE_TORCH);		
							camera.setParameters(params);
							camera.startPreview();
								
							curentMode= ON_LED_MODE;
							 if (!prefs.getBoolean("led_block", false)){
								   resiverRegistred=true;
								   context.getApplicationContext().registerReceiver(torchReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF)); 
								 
							   } 	
						} catch (RuntimeException e) {	
							 curentMode= ON_SCREEN_MODE;
						}
					}															
				 }
				 else{
					 
					 if (getCount(context)==0 && cameraId>=0){
						 	showDialog(context);					 
					 }
					 curentMode= ON_SCREEN_MODE;
				 }
				
				if (runedFrom==RUN_FROM_WIDGET && MainFastTorchActivity.handleToClose!=null){
					  MainFastTorchActivity tmpa=(MainFastTorchActivity)MainFastTorchActivity.handleToClose;
					  tmpa.UpdateState();
				}
				
		return curentMode;
	}
	
	 private static void OffTorch(Context context){
		  
		  if (camera!=null){
			  
			Parameters params = camera.getParameters();
			params.setFlashMode(Parameters.FLASH_MODE_OFF);
			camera.stopPreview();
	        camera.release();
	        
	        
	            
		  }
       
	 
//		  Context context1= context.getApplicationContext();
//		    KeyguardManager _guard = (KeyguardManager) context1.getSystemService(Context.KEYGUARD_SERVICE);
//		    KeyguardLock _keyguardLock = _guard.newKeyguardLock("KeyguardLockWrapper");
//		    //to disable
////		    _keyguardLock.disableKeyguard();
//		    //to enable
//		    _keyguardLock.reenableKeyguard();
//		    
//		    DevicePolicyManager mDPM = (DevicePolicyManager)context1.getSystemService(Context.DEVICE_POLICY_SERVICE);
//		    ComponentName mAdminName = new ComponentName(context1,MainFastTorchActivity.class);
//		    
//		    Intent intent = new       
//		    		Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//		    
//		    if(!mDPM.isAdminActive(mAdminName))
//	        {
//	             intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//	            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
//	              intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"is locked");
//	              intent.putExtra("force-locked", DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
//
////	            startActivityForResult(intent, 1);
//	            System.out.println("The Device Could not lock because device admin not enabled");
////	            mDPM.lockNow();
//	        }
//	        else
//	        {
//	            System.out.println("The Device  device admin enabled");
//	             intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
//	            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mAdminName);
//	              intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"onEnabled");
//	            mDPM.lockNow();
//	            mDPM.setMaximumTimeToLock(mAdminName, 0);
//	              intent.putExtra("force-locked", DeviceAdminInfo.USES_POLICY_FORCE_LOCK);
////
////	              context1.startActivityForResult(intent, 1);
//
//	        }  
		    
		  curentMode=OFF_MODE;
		  camera=null;
		  cameraId=-1;	
		  
		  if (resiverRegistred){
			   context.unregisterReceiver(torchReceiver);	
			   resiverRegistred=false;
			   }
		  
		  prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
		  if (prefs.getBoolean("led_notif", true)){
			  mNotifyMgr.cancel(GlobalLogic.NOTIFY_ID);
	      }
	 }
	
	private static Boolean resiverRegistred=false;
	 private static BroadcastReceiver torchReceiver = new BroadcastReceiver(){  
		  
	     @Override  
	     public void onReceive(Context context, Intent intent) {  
	      
	    	 GlobalLogic.isScreenOff=true;
	    	 OffTorch(context);
	    	 prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
	    	 if (!prefs.getBoolean("led_block", false)){				  
	    		 onTorch(context);
	    	 }
	    	 
	     }  
	    
	}; 

	public static void SendNotify(Context context){
		
		prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
		 if (prefs.getBoolean("led_notif", true)){
			 
		 mNotifyMgr = (NotificationManager)context.getSystemService( 
	        		Context.NOTIFICATION_SERVICE); 
			int icon = R.drawable.ic_launcher; 
			
        CharSequence tickerText = context.getString(R.string.app_name); 
        long when = System.currentTimeMillis(); 
        
		 Notification notification = new Notification(icon, tickerText, when);
         notification.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
       
         CharSequence contentTitle = "FastTorch"; 
         CharSequence contentText = context.getString(R.string.of_light_notif);
         
         Intent notificationIntent = new Intent( 
      		   context, Receiver.class);
         notificationIntent.setAction(ACTION_OFF_RECEIVER);
         
         PendingIntent contentIntent = PendingIntent.getBroadcast(context, 0, notificationIntent, 0); 
         
                 
         notification.setLatestEventInfo(context, contentTitle, 
                 contentText, contentIntent); 
         
        	 mNotifyMgr.notify(NOTIFY_ID, notification);
         }
                         
	}
	
	public static void closeApp(Context context){
		
		
		int brightnessMode=-1;
		Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, brightnessMode);
		
		if (MainFastTorchActivity.handleToClose!=null && CheckCount(context)){
			if (curentMode==ON_LED_MODE){
				OffTorch(context);
				updateWidgets(context);
	 		}
			curentMode=OFF_MODE;
			runedFrom=RUN_FROM_ACTIVITY;
			mDialog.onShow();
			
			isScreenOff=false;	
		}
		else{
			if (!isScreenOff || prefs.getBoolean("led_block", false)){
				prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
				if (Integer.parseInt(prefs.getString("what_do_p", "0"))!=0){
					if (MainFastTorchActivity.handleToClose!=null){
						MainFastTorchActivity.handleToClose.moveTaskToBack(true);
					}
				}
				else{	
					if (curentMode!=EXIT_MODE){
						if (curentMode==ON_LED_MODE){
							OffTorch(context);
				 		}
						curentMode=EXIT_MODE;		
						updateWidgets(context);
					}
					if (readyToExitBig && readyToExitSmall){
						curentMode=OFF_MODE;
						runedFrom=RUN_FROM_ACTIVITY;
						
						
						  
						if (MainFastTorchActivity.handleToClose!=null){
							
							try {
					 			 if (GlobalLogic.brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
								     Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
								 }
						 		 else{
						 			Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, brighness);
						 		 }					 		
							} catch (Exception e) {
								// TODO: handle exception
							}
							
							MainFastTorchActivity tmpa=(MainFastTorchActivity)MainFastTorchActivity.handleToClose;
							tmpa.lockDevice(false);
							
							
					 		MainFastTorchActivity.handleToClose.finish();
					 		MainFastTorchActivity.handleToClose=null;
					 		
					 		
					 	}
						//android.os.Process.killProcess(android.os.Process.myPid());
						
						
					}		 
				}		 	
			}

			isScreenOff=false;		
		}
		
	}
	
	public static void updateWidgets(Context context){
		
		Intent intent = new Intent(context,FastTorchWidget.class);
		   intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		   context.sendBroadcast(intent);
		   
		   intent = new Intent(context,FastTorchBigWidget.class);
		   intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		   context.sendBroadcast(intent);
	}
	 
	
	public static int onOffTorch(Context context){
		
		KeyguardManager kgManager = (KeyguardManager)context.getSystemService(Activity.KEYGUARD_SERVICE);
		KeyguardLock kLock = kgManager.newKeyguardLock("****");
		kLock.disableKeyguard();
		
		prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
		if (curentMode==PREF_MODE) return PREF_MODE;
		
		if (Integer.parseInt(GlobalLogic.prefs.getString("def_Lihgt", "0"))!=0 && cameraId<=-1){
			curentMode=ON_SCREEN_MODE;
			if (runedFrom==RUN_FROM_WIDGET && !prefs.getBoolean("widget_pref", false)){
				   runScreenTorch(context);
			   }
			return curentMode;
		}
		
	   if (curentMode==OFF_MODE){  
		   
		   if (runedFrom==RUN_FROM_WIDGET && !prefs.getBoolean("widget_pref", false)){
			   runScreenTorch(context);
		   }
		   
		   SendNotify(context);
		   updateWidgets(context);
		   onTorch(context);
		  
		   
		
	   }
		  
	   else if (curentMode==ON_LED_MODE){
		   
		   updateWidgets(context); 
		   OffTorch(context);
		   if (runedFrom==RUN_FROM_WIDGET && !prefs.getBoolean("widget_pref", false)){
			   closeApp(context);
		   }
	   }
	   	  return curentMode;		   
	 }
	
}
